package com.qf.medicaldoctoradmin.healthHead.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.common.entity.Articles;
import com.qf.common.enums.HealthHeadRedisKeyEnum;
import com.qf.common.utils.DateUtils;
import com.qf.common.utils.RedisUtils;
import com.qf.medicaldoctoradmin.healthHead.article.dao.HealthHeadDao;
import com.qf.medicaldoctoradmin.healthHead.article.param.UpdateArticleParam;
import com.qf.medicaldoctoradmin.healthHead.article.service.HealthHeadService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HealthHeadServiceImpl implements HealthHeadService {
    @Resource
    private HealthHeadDao healthHeadDao;

    @Override
    public List<Articles> selectList() {
        List<Articles> articles = (List<Articles>) RedisUtils.getValue(HealthHeadRedisKeyEnum.KEY_HEALTH_HEADLINE.getKey());
        if (articles == null) {
            articles = healthHeadDao.selectList(new LambdaQueryWrapper<Articles>());
            RedisUtils.setValueTimeout(HealthHeadRedisKeyEnum.KEY_HEALTH_HEADLINE.getKey(), articles, 30 *24 * 3600);
        }
        return articles;
    }

    @Override
    public void updateCollectNum() {
        //获取昨天日期字符串
        String yyyyMMdd = DateUtils.formatDate(DateUtils.yesterday(), "yyyyMMdd");
        // 为了演示方便，获取当天的点赞数据进行更新
//        String yyyyMMdd = DateUtils.formatDate(new Date(), "yyyyMMdd");
        String key = String.format("collectNum:%s",yyyyMMdd);
        //获取hash中所有的数据（key和value） 返回对象中，key是文章的id，value是头一天的点赞数
        Map<Object, Object> map = RedisUtils.hashGetAll(key);
        List<UpdateArticleParam> list = new ArrayList<>();
        //map 使用keySet进行遍历数据
        for (Object k : map.keySet()) {
            UpdateArticleParam p = new UpdateArticleParam();
            Integer v =Integer.valueOf(k.toString());
            if (!v.equals(0)) {
                p.setArticlesId(Integer.valueOf(k.toString()));
                p.setCollectNum(v);
                list.add(p);
            }
        }
        //分批的批量更新，比如一次更新100条
        int count = 0;
        if (list.size() > 0) {
            ArrayList<UpdateArticleParam> temp = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                temp.add(list.get(i));
                count++;
                if (count == 100) {
                    //批量更新
                    healthHeadDao.updateBatch(temp);
                    count = 0;
                    temp.clear();
                }
            }
            if (temp.size() > 0) {
                //批量更新
                healthHeadDao.updateBatch(temp);
            }

        }
    }
}
